package cn.edu.sdju.wanglo1911.team10.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import cn.edu.sdju.wanglo1911.team10.po.AdminAccount;
import cn.edu.sdju.wanglo1911.team10.po.Book;
import cn.edu.sdju.wanglo1911.team10.po.OrderItem;
import cn.edu.sdju.wanglo1911.team10.po.OrderSummary;
import cn.edu.sdju.wanglo1911.team10.service.AdminAccountService;
import cn.edu.sdju.wanglo1911.team10.service.BookService;
import cn.edu.sdju.wanglo1911.team10.service.OrderService;
import cn.edu.sdju.wanglo1911.team10.service.Sha256Service;
import cn.edu.sdju.wanglo1911.team10.service.UserAccountService;
import cn.edu.sdju.wanglo1911.team10.utillity.Helper;
import cn.edu.sdju.wanglo1911.team10.po.QueryOption;
import cn.edu.sdju.wanglo1911.team10.po.UserAccount;

@Controller
@RequestMapping("/admin")
public class AdminController {
	
	@Autowired
	private AdminAccountService adminAccountService;
	@Autowired
	private BookService bookService;
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private Sha256Service sha256Service;
	
	@RequestMapping("/panel")
	public String panel(HttpServletRequest request,HttpSession session,Model model) {
		model.addAttribute("account", session.getAttribute("admin_account"));
		return "panel";
	}
	
	@RequestMapping("/panel/user")
	public String userPanel(HttpServletRequest request,QueryOption option, String error,HttpSession session,Model model) {
		model.addAttribute("account", session.getAttribute("admin_account"));
		model.addAttribute("error", error);
		String redirect = request.getQueryString();
		List<UserAccount> userAccounts =userAccountService.advanceQuery(option);
		Integer total = userAccountService.getTotalQueryNumber(option);
		Integer pages = (int) Math.ceil(total / 10.0);
		Integer currPage = (int) Math.ceil((option.getFirst()+1) / 10.00);
		model.addAttribute("userAccounts", userAccounts);
		model.addAttribute("currPage", currPage);
		model.addAttribute("pages", pages);
		model.addAttribute("queryOption", option);
		model.addAttribute("redirect", redirect);
		return "user_panel";
	}
	
	@PostMapping("panel/user/delete") 
	public String deleteUserAccounts(HttpServletRequest request,String[] id,String redirect,Model model) {
		List<String> ids = Arrays.asList(id);
		try {
			userAccountService.deleteUserAccountByIds(ids);
		} catch (Exception e) {
			model.addAttribute("error", "删除失败");
		}
		return "redirect:/admin/panel/user"+ (redirect != null && !redirect.equals("") ? "?"+redirect : "");
	}
	
	@RequestMapping("/panel/user/edit/{id}")
	public String editUser(HttpServletRequest request,@PathVariable String id, UserAccount newUser,HttpSession session,Model model) {
		model.addAttribute("account", session.getAttribute("admin_account"));
		QueryOption option = new QueryOption();
		option.setQueryType("userId");
		option.setQuery(id);
		List<OrderSummary> orderSummaries = orderService.advanceQuery(option);
		model.addAttribute("orderSummaries", orderSummaries);
		if ("POST".equals(request.getMethod())) {
			if (newUser.getPassword() != null && !newUser.getPassword().equals(""))
				newUser.setPassword(sha256Service.digest(newUser.getPassword()));
			userAccountService.updateUserAccount(newUser);
		}
		UserAccount userAccount = userAccountService.getUserAccountById(id);
		model.addAttribute("code", 200);
		model.addAttribute("userAccount", userAccount);
		return "edit_user";
	}
	
	@RequestMapping("/panel/book")
	public String bookPanel(HttpServletRequest request,QueryOption option, HttpSession session,Model model) {
		model.addAttribute("account", session.getAttribute("admin_account"));
		List<Book> books = bookService.advanceQuery(option);
		String redirect = request.getQueryString();
		Integer total = bookService.getTotalQueryNumber(option);
		Integer pages = (int) Math.ceil(total / 10.0);
		Integer currPage = (int) Math.ceil((option.getFirst()+1) / 10.00);
		model.addAttribute("books", books);
		model.addAttribute("currPage", currPage);
		model.addAttribute("pages", pages);
		model.addAttribute("queryOption", option);
		model.addAttribute("redirect", redirect);
		return "book_panel";
	}
	@RequestMapping("/panel/book/edit/{id}")
	public String editBook(HttpServletRequest request,@PathVariable String id, Book newBook,HttpSession session,Model model) {
		model.addAttribute("account", session.getAttribute("admin_account"));
		if ("GET".equals(request.getMethod())) {
			System.out.println(id);
		} else if ("POST".equals(request.getMethod())) {
			bookService.updateBook(newBook);	
		}
		Book book = bookService.getBookById(id);
		model.addAttribute("code", 200);
		model.addAttribute("book", book);
		return "edit_book";
	}
	@GetMapping("/panel/book/new")
	public String newBook(HttpServletRequest request,HttpSession session,Model model) {
		model.addAttribute("account", session.getAttribute("admin_account"));
		return "new_book";
	}
	@PostMapping("/panel/book/new")
	public String newBookPost(HttpServletRequest request, Book newBook,MultipartFile bookImg, HttpSession session,Model model) {
		model.addAttribute("account", session.getAttribute("admin_account"));
		String ext = Helper.getExt(bookImg.getOriginalFilename());
		String prefix = session.getServletContext().getRealPath("/static/imgs/"+newBook.getId()+".png");
		File file = new File(prefix);
		try {
			bookImg.transferTo(file);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		bookService.insertBook(newBook);
		return "redirect:/admin/panel/book";
	}
	@RequestMapping(value = "panel/book/delete",method = RequestMethod.POST) 
	public String deleteBooks(HttpServletRequest request,String[] id,String redirect,Model model) {
		List<String> ids = Arrays.asList(id);
		try {
			bookService.deleteBookByIds(ids);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("删除失败");
		}
		return "redirect:/admin/panel/book"+ (redirect != null && !redirect.equals("") ? "?"+redirect : "");
	}
	
	
	
	@RequestMapping("/panel/order")
	public String userOrder(HttpServletRequest request,QueryOption option, HttpSession session,Model model) {
		model.addAttribute("account", session.getAttribute("admin_account"));
		List<OrderSummary> orderSummaries = orderService.advanceQuery(option);
		String redirect = request.getQueryString();
		Integer total = orderService.getTotalQueryNumber(option);
		Integer pages = (int) Math.ceil(total / 10.0);
		Integer currPage = (int) Math.ceil((option.getFirst()+1) / 10.00);
		model.addAttribute("orderSummaries", orderSummaries);
		model.addAttribute("currPage", currPage);
		model.addAttribute("pages", pages);
		model.addAttribute("queryOption", option);
		model.addAttribute("redirect", redirect);
		return "order_panel";
	}
	
	@RequestMapping(value = "panel/order/delete",method = RequestMethod.POST) 
	public String deleteOrder(HttpServletRequest request,String[] orderNos,String redirect,Model model) {
		if (orderNos != null) {
			List<String> nos = Arrays.asList(orderNos);
			orderService.deleteAllByOrderNo(nos);
		}
		return "redirect:/admin/panel/order?"+redirect;
	}
	
	@GetMapping("/panel/order/view/{orderNo}")
	public String viewOrder(HttpServletRequest request,@PathVariable String orderNo, Book newBook,HttpSession session,Model model) {
		model.addAttribute("account", session.getAttribute("admin_account"));
		List<OrderItem> orderItems = orderService.getAllItemByOrderNo(orderNo);
		UserAccount user_account = userAccountService.getUserAccountById(orderItems.get(0).getUserId());
		model.addAttribute("orderNo", orderNo);
		model.addAttribute("orderItems", orderItems);
		model.addAttribute("orderStatus", orderItems.get(0).getStatus());
		model.addAttribute("user_account", user_account);
		return "view_order";
	}
	
	@PostMapping("/panel/order/view/{orderNo}")
	public String updateOrder(HttpServletRequest request,@PathVariable String orderNo, Integer status,HttpSession session,Model model) {
		OrderSummary order = new OrderSummary();
		order.setOrderNo(orderNo);
		order.setStatus(status);
		orderService.updateOrder(order);
		return "redirect:/admin/panel/order/view/"+orderNo;
	}
	
	@RequestMapping("/login")
	public String login(HttpServletRequest request,String nick,String password, String redirect,HttpSession session,Model model) {
		if ("GET".equals(request.getMethod())) {
			model.addAttribute("loginTitle", "管理员登录");
			model.addAttribute("redirect", redirect);
			model.addAttribute("helpMessage", "然而并没有帮助👻");
			return "admin_login";
		}
		AdminAccount admin_account = adminAccountService.getAdminAccountByNick(nick);
		if (admin_account != null && admin_account.getPassword().equals(password)) {
			session.setAttribute("admin_account", admin_account);
			if (redirect == null || redirect.equals("")) {
				redirect = "/admin/panel";
			}
			return "redirect:" + redirect;
		}
		model.addAttribute("loginTitle", "管理员登录");
		model.addAttribute("redirect", redirect);
		model.addAttribute("helpMessage", "然而并没有帮助👻");
		model.addAttribute("error", "管理员用户名或密码错误");
		return "admin_login";
	}
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,HttpSession session,Model model) {
		if (session != null) {
			session.removeAttribute("admin_account");
		}	
		return "redirect:/admin/login";
	}
}
